import { Router, Request, Response } from 'express';
import multer, { FileFilterCallback } from 'multer';
import path from 'path';
import fs from 'fs';
import { v4 as uuidv4 } from 'uuid';
import { BaiduOCRService } from '../../sdk/baidu/ocr';
import Jimp from 'jimp';

const router = Router();

// 使用内存存储
const storage = multer.memoryStorage();

// 文件类型过滤器
const fileFilter = (_req: Request, file: Express.Multer.File, cb: FileFilterCallback) => {
  const allowedTypes = ['image/jpeg', 'image/png', 'application/pdf'];

  if (allowedTypes.includes(file.mimetype)) {
    cb(null, true);
  } else {
    cb(new Error('不支持的文件类型'));
  }
};

// 处理文件保存
async function saveFile(file: Express.Multer.File): Promise<{ filepath: string, filename: string }> {
  const appConfig = require('../../config/app').default;
  const today = new Date().toISOString().split('T')[0];
  let uploadDir = `${appConfig.uploadPath}/${today}`;

  console.info(`开始处理文件: ${file.originalname}, 大小: ${file.size} bytes, 类型: ${file.mimetype}`);

  if (uploadDir.startsWith('../')) {
    uploadDir = uploadDir.replace('../', '');
  }

  if (!fs.existsSync(uploadDir)) {
    fs.mkdirSync(uploadDir, { recursive: true });
    console.log(`创建上传目录: ${uploadDir}`);
  }

  let buffer = file.buffer;

  // 检查是否需要压缩
  if (file.size > 2 * 1024 * 1024 && file.mimetype.startsWith('image/')) {
    console.log(`文件大小超过2MB，开始压缩: ${file.originalname}`);
    try {
      const image = await Jimp.read(buffer);
      image.scaleToFit(1920, 1080);
      buffer = await image.quality(80).getBufferAsync(Jimp.MIME_JPEG);
      console.log(`压缩完成，压缩后大小: ${buffer.length} bytes，压缩率: ${((1 - buffer.length / file.size) * 100).toFixed(2)}%`);
    } catch (error) {
      console.log(`图片压缩失败: ${error}`);
      // 如果压缩失败，使用原始文件
      buffer = file.buffer;
    }
  }

  const filename = `${uuidv4()}${path.extname(file.originalname)}`;
  const filepath = path.join(uploadDir, filename);

  await fs.promises.writeFile(filepath, buffer);
  console.log(`文件保存成功: ${filepath}`);

  return {
    filepath,
    filename
  };
}

// 身份证识别接口
router.post('/idcard', multer({ storage, fileFilter, limits: { fileSize: 10 * 1024 * 1024 } }).single('file'), async (req: Request, res: Response) => {
  try {
    if (!req.file) {
      console.log('身份证识别：未上传文件');
      return res.status(400).json({ success: false, message: '未上传文件' });
    }

    if (!req.body.side || !['front', 'back'].includes(req.body.side)) {
      console.log(`身份证识别：无效的面向参数: ${req.body.side}`);
      return res.status(400).json({ success: false, message: '请指定身份证正反面(front/back)' });
    }

    console.log(`开始处理身份证识别请求，面向: ${req.body.side}`);

    // 保存并处理文件
    const { filepath, filename } = await saveFile(req.file);

    // 读取文件并转换为 base64
    const image = fs.readFileSync(filepath).toString('base64');
    console.log('文件转换为base64完成，准备调用OCR服务');

    // 调用百度 OCR 识别
    const result = await BaiduOCRService.recognizeIDCard(image, req.body.side);
    console.log('OCR识别完成');

    const today = new Date().toISOString().split('T')[0];
    return res.json({
      success: true,
      data: {
        filePath: `/uploads/${today}/${filename}`,
        ...result
      }
    });
  } catch (error: any) {
    console.log('身份证识别失败:', error);
    return res.status(500).json({
      success: false,
      message: error.message
    });
  }
});

// 营业执照识别接口
router.post('/business-license', multer({ storage, fileFilter, limits: { fileSize: 10 * 1024 * 1024 } }).single('file'), async (req: Request, res: Response) => {
  try {
    if (!req.file) {
      console.log('营业执照识别：未上传文件');
      return res.status(400).json({ success: false, message: '未上传文件' });
    }

    console.log('开始处理营业执照识别请求');

    // 保存并处理文件
    const { filepath, filename } = await saveFile(req.file);

    // 读取文件并转换为 base64
    const image = fs.readFileSync(filepath).toString('base64');
    console.log('文件转换为base64完成，准备调用OCR服务');

    // 调用百度 OCR 识别
    const result = await BaiduOCRService.recognizeBusinessLicense(image);
    console.log('OCR识别完成');

    const today = new Date().toISOString().split('T')[0];

    return res.json({
      success: true,
      data: {
        filePath: `/uploads/${today}/${filename}`,
        ...result
      }
    });
  } catch (error: any) {
    console.log('营业执照识别失败:', error);
    return res.status(500).json({
      success: false,
      message: error.message
    });
  }
});

export default router;